package nsu.edu.zsq.filter;

import java.io.IOException;
import java.util.List;
import java.util.Set;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.common.base.Splitter;
import com.google.common.collect.Sets;

import lombok.extern.slf4j.Slf4j;
import nsu.edu.zsq.bean.SysUser;
import nsu.edu.zsq.common.RequestHolder;

/** 
* Description: 权限拦截器<br>
*/
@Slf4j
public class AclControlFilter implements Filter{
    
    private static Set<String> exclusionUrlSet = Sets.newConcurrentHashSet();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
            throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        SysUser sysUser = RequestHolder.getCurrentSysUser();
        if (sysUser.getType() == 0) {
            // 如果是超级管理员，直接放行
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        } else {
            // 其它管理员，判断是否有权限访问
            List<String> exclusionUrlList = Splitter.on(";").trimResults().omitEmptyStrings().splitToList(sysUser.getBanUrl());
            exclusionUrlSet = Sets.newConcurrentHashSet(exclusionUrlList);
            String url = request.getRequestURI().toString();
            for (String exclusionUrl: exclusionUrlSet) {
                if (url.startsWith(exclusionUrl)) {
                    log.info("请求的地址：{}，无权限访问",url);
                    request.getRequestDispatcher("/sys/toNoAuth").forward(request, response);
                    return;
                }
            }
        }
        filterChain.doFilter(servletRequest, servletResponse);
        return;
    }

}
